//
//  Liu70CountDownLabel.m
//
//  Created by Liu70 on 2018/2/3.
//  Copyright © 2018年 Liu70. All rights reserved.
//

#import "Liu70CountDownLabel.h"

@interface Liu70CountDownLabel ()

@property (nonatomic, strong) NSDate *endDate;
@property (nonatomic, strong) NSTimer *timer;

@end

@implementation Liu70CountDownLabel

- (void)dealloc {
    [self stopCountDown];
}

- (void)startCountDownToEndDate:(NSDate*)endDate finish:(Finish)finish {
    self.endDate = endDate;
    [self stopCountDown];
    self.text = [self timeStringForTimeInterval:[self.endDate timeIntervalSinceNow]];
    __weak typeof(self) weakSelf = self;
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0 repeats:YES block:^(NSTimer * _Nonnull timer) {
        NSTimeInterval timeInterval = [weakSelf.endDate timeIntervalSinceNow];
        if (timeInterval <= 0) {
            [weakSelf stopCountDown];
            finish();
        } else {
            weakSelf.text = [weakSelf timeStringForTimeInterval:timeInterval];
        }
    }];
}

- (void)stopCountDown {
    [self.timer invalidate];
    self.timer = nil;
    self.text = @"";
}

- (NSString*)timeStringForTimeInterval:(NSTimeInterval)timeInterval {
    NSString *timeString = @"";
    
    int intTimeInterval = (int)(timeInterval + 0.01);
    
    int days = (int)intTimeInterval / 86400;
    int hours = ((int)intTimeInterval / 3600) % 24;
    int minutes = ((int)intTimeInterval / 60) % 60;
    int seconds = (int)intTimeInterval % 60;
    timeString = days == 0 ? timeString : [timeString stringByAppendingString:[NSString stringWithFormat:@"%d天", days]];
    timeString = hours == 0 ? timeString : [timeString stringByAppendingString:[NSString stringWithFormat:@"%d小时", hours]];
    timeString = minutes == 0 ? timeString : [timeString stringByAppendingString:[NSString stringWithFormat:@"%d分", minutes]];
    timeString = seconds == 0 ? timeString : [timeString stringByAppendingString:[NSString stringWithFormat:@"%d秒", seconds]];
    
    return timeString;
}

@end
